Skip to content
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

Nextjs 13 / Cypress: TypeError: Cannot convert undefined or null to object #6059

Closed
3 tasks done
geryit opened this issue Oct 27, 2022 · 5 comments · Fixed by #6072
Closed
3 tasks done

Nextjs 13 / Cypress: TypeError: Cannot convert undefined or null to object #6059

geryit opened this issue Oct 27, 2022 · 5 comments · Fixed by #6072

Comments

@geryit
Copy link

geryit commented Oct 27, 2022

Is there an existing issue for this?

How do you use Sentry?

Sentry Saas (sentry.io)

Which package are you using?

@sentry/nextjs

SDK Version

7.16.0

Framework Version

7.16.0

Link to Sentry event

No response

Steps to Reproduce

We upgraded to Nextjs 13 and @sentry/nextjs to 7.16.0 yesterday and started to see this in CircleCI on Cypress job:

/home/circleci/project/node_modules/@sentry/nextjs/cjs/utils/instrumentServer.js:77
      const serverPrototype = Object.getPrototypeOf(liveServer);
                                     ^

TypeError: Cannot convert undefined or null to object
    at Function.getPrototypeOf (<anonymous>)
    at NextServer.wrappedHandlerGetter (/home/circleci/project/node_modules/@sentry/nextjs/cjs/utils/instrumentServer.js:77:38)
    at /home/circleci/project/node_modules/next/dist/server/next.js:78:47
    at Server.<anonymous> (/home/circleci/project/node_modules/next/dist/server/lib/start-server.js:17:16)
    at Server.emit (node:events:513:28)
    at Server.emit (node:domain:489:12)
    at parserOnIncoming (node:_http_server:998:12)
    at HTTPParser.parserOnHeadersComplete (node:_http_common:128:17)
Error: server closed unexpectedly
    at ChildProcess.onClose (/home/circleci/project/node_modules/start-server-and-test/src/index.js:75:14)
    at ChildProcess.emit (node:events:513:28)
    at maybeClose (node:internal/child_process:1100:16)
    at Process.ChildProcess._handle.onexit (node:internal/child_process:304:5)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Exited with code exit status 1
CircleCI received exit code 1

Expected Result

No errors so Cypress doesn't exit

Actual Result

/home/circleci/project/node_modules/@sentry/nextjs/cjs/utils/instrumentServer.js:77
      const serverPrototype = Object.getPrototypeOf(liveServer);
                                     ^

TypeError: Cannot convert undefined or null to object
    at Function.getPrototypeOf (<anonymous>)
    at NextServer.wrappedHandlerGetter (/home/circleci/project/node_modules/@sentry/nextjs/cjs/utils/instrumentServer.js:77:38)
    at /home/circleci/project/node_modules/next/dist/server/next.js:78:47
    at Server.<anonymous> (/home/circleci/project/node_modules/next/dist/server/lib/start-server.js:17:16)
    at Server.emit (node:events:513:28)
    at Server.emit (node:domain:489:12)
    at parserOnIncoming (node:_http_server:998:12)
    at HTTPParser.parserOnHeadersComplete (node:_http_common:128:17)
Error: server closed unexpectedly
    at ChildProcess.onClose (/home/circleci/project/node_modules/start-server-and-test/src/index.js:75:14)
    at ChildProcess.emit (node:events:513:28)
    at maybeClose (node:internal/child_process:1100:16)
    at Process.ChildProcess._handle.onexit (node:internal/child_process:304:5)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Exited with code exit status 1
CircleCI received exit code 1
@lforst
Copy link
Member

lforst commented Oct 27, 2022

Hi, thanks for writing in! Since Next.js 13 is quite new and the sources of errors are currently quite unclear, can I ask you to do two things to make debugging this easier?

  • A small reproduction example
  • Can you try removing the SDK from your project entirely and try running the tests again? I wanna make sure this isn't another package causing an error and we're just the ones to surface it.

Thank you!

@jmaestree
Copy link

jmaestree commented Oct 27, 2022

Hi @lforst !! I've the same issue when building my app inside a Docker image, let's see if this helps you to detect the issue.

I've tried the following (which didn't work for me):

  1. Disable autoInstrument option
sentry: {
    autoInstrumentServerFunctions: false,
  },

☝️ This didn't work for me, and I decided to:

  1. Avoid call withSentryConfig in next.config.js file:
const SENTRY_ENABLED = false;
  if (SENTRY_ENABLED && process.env.NODE_ENV !== 'development') {
    config = withSentryConfig(config, {
      silent: true,
      url: process.env.SENTRY_URL,
      org: process.env.SENTRY_ORG,
      project: process.env.SENTRY_PROJECT,
      authToken: process.env.SENTRY_AUTH_TOKEN,
    });
  }

After adding this piece of code and build the docker image again, the error still persists.

So I decided to manually add a console.log(this) in this line (before the line which causes the error) and my app output the following:

NextServer {
  options: {
    dir: '/home/node',
    hostname: 'localhost',
    port: 8080,
    keepAliveTimeout: undefined,
    customServer: false,
    httpServer: Server {
      maxHeaderSize: undefined,
      insecureHTTPParser: undefined,
      requestTimeout: 300000,
      headersTimeout: 60000,
      keepAliveTimeout: 5000,
      connectionsCheckingInterval: 30000,
      _events: [Object: null prototype],
      _eventsCount: 5,
      _maxListeners: undefined,
      _connections: 2,
      _handle: [TCP],
      _usingWorkers: false,
      _workers: [],
      _unref: false,
      allowHalfOpen: true,
      pauseOnConnect: false,
      noDelay: true,
      keepAlive: false,
      keepAliveInitialDelay: 0,
      httpAllowHalfOpen: false,
      timeout: 0,
      maxHeadersCount: null,
      maxRequestsPerSocket: 0,
      _connectionKey: '4:0.0.0.0:8080',
      [Symbol(IncomingMessage)]: [Function: IncomingMessage],
      [Symbol(ServerResponse)]: [Function: ServerResponse],
      [Symbol(kCapture)]: false,
      [Symbol(async_id_symbol)]: 10,
      [Symbol(http.server.connections)]: ConnectionsList {},
      [Symbol(http.server.connectionsCheckingInterval)]: Timeout {
        _idleTimeout: 30000,
        _idlePrev: [TimersList],
        _idleNext: [TimersList],
        _idleStart: 945,
        _onTimeout: [Function: bound checkConnections],
        _timerArgs: undefined,
        _repeat: 30000,
        _destroyed: false,
        [Symbol(refed)]: false,
        [Symbol(kHasPrimitive)]: false,
        [Symbol(asyncId)]: 7,
        [Symbol(triggerId)]: 0
      },
      [Symbol(kUniqueHeaders)]: null
    }
  },
  serverPromise: Promise { <pending> }
}

The line which causes the error is trying to get the server from this.server (is returning null):

liveServer = this.server;
const serverPrototype = Object.getPrototypeOf(liveServer);

So I've two questions:

  • How I can disable fully the @sentry/nextjs library to prevent this error to appear and don't block my feature? Should I delete the sentry.client.config.ts and sentry.server.config.ts files too?
  • By other side, do you know if there're any changes on Nextjs 13 that changed the property from this.server to this.httpServer?

Thank you in advance,

@jmaestree
Copy link

Hi again @lforst ,

I did another test which solved the issue, but I don't know if is the right implementation.

I noticed that the console.log(this) is returning a serverPromise: Promise { <pending> }.
I've added an await before accessing to the server:

// packages/nextjs/src/utils)/instrumentServer.ts 
// Line 31
const wrappedHandlerGetter = async function (this: NextServer): Promise<ReqHandler> {
    if (!sdkSetupComplete) {
      // NEW --> Await for the server promise
      await this.serverPromise;

      // stash this in the closure so that `makeWrappedReqHandler` can use it
      liveServer = this.server;
      const serverPrototype = Object.getPrototypeOf(liveServer);
      ...

After adding that line, the server is working again.

@lforst
Copy link
Member

lforst commented Oct 27, 2022

Ah thank you so much for debugging this. I think you might be correct in your assumptions and we need to somehow await the server.

I am still wondering why I can't reproduce this - maybe it's a race condition.

As for your questions:

How I can disable fully the @sentry/nextjs library to prevent this error to appear and don't block my feature? Should I delete the sentry.client.config.ts and sentry.server.config.ts files too?

I would suggest literally ripping out everything related to Sentry but I don't think this is necessary anymore since you probably identified the issue.

By other side, do you know if there're any changes on Nextjs 13 that changed the property from this.server to this.httpServer?

Looking at Next.js' code it doesn't seem like they changed it to this.httpServer.

@lforst
Copy link
Member

lforst commented Oct 27, 2022

I opened a PR #6072 that should address this (not yet sure if we're gonna merge it). I opted not to await serverPromise because that field might potentially not be defined (at least typing wise) when getServerRequestHandler is called:

https://github.com/vercel/next.js/blob/0beed3563cdab846fd6b683f1ed5586de3e7d96d/packages/next/server/next.ts#L42

Instead we're simply awaiting getServer which seems safe-ish.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants