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

Getting "ReferenceError: Response is not defined" while trying to upgrade an app from next 11 to next 12 #30398

Closed
andreisena opened this issue Oct 27, 2021 · 7 comments · Fixed by #31935 or #32368
Assignees
Labels
Middleware Related to Next.js Middleware.

Comments

@andreisena
Copy link

What version of Next.js are you using?

12.0.0

What version of Node.js are you using?

16.3.0

What browser are you using?

Chrome

What operating system are you using?

macOS

How are you deploying your application?

next build + next start

Describe the Bug

I am trying to upgrade Next.js version in a big application from v11.0.1 to Next.js 12. It uses Next with express.js.
I'm getting the following error:

ReferenceError: Response is not defined
    at Object.<anonymous> (/Users/andreisena/projects/.../node_modules/next/dist/server/web/spec-extension/response.js:23:28)
    at Module._compile (node:internal/modules/cjs/loader:1109:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1138:10)
    at Module.load (node:internal/modules/cjs/loader:989:32)
    at Function.Module._load (node:internal/modules/cjs/loader:829:14)
    at Function.wrappedLoad [as _load] (/Users/andreisena/projects/.../node_modules/newrelic/lib/shimmer.js:373:24)
    at Module.require (node:internal/modules/cjs/loader:1013:19)
    at require (node:internal/modules/cjs/helpers:93:18)
    at Object.<anonymous> (/Users/andreisena/projects/.../node_modules/next/dist/server/next-server.js:47:17)
    at Module._compile (node:internal/modules/cjs/loader:1109:14)

Expected Behavior

To work correctly like v11

To Reproduce

I couldn't reproduce it yet on a fresh install of Next.js and I cannot share the repo since it is private. But if I find something new I will post here.

What I could see in a fresh install is that when I debug Response in server/web/spec-extension/response.js, it has the same contract as node-fetch Response. Is that correct?

Object [Response] {
  url: [Getter],
  status: [Getter],
  ok: [Getter],
  redirected: [Getter],
  statusText: [Getter],
  headers: [Getter],
  clone: [Function: clone],
  body: [Getter],
  bodyUsed: [Getter],
  arrayBuffer: [Function: arrayBuffer],
  blob: [Function: blob],
  json: [Function: json],
  text: [Function: text],
  buffer: [Function: buffer],
  textConverted: [Function: textConverted]
}

By the way, on the main application, Response always come as undefined.

@andreisena andreisena added the bug Issue was opened via the bug report template. label Oct 27, 2021
@ijjk
Copy link
Member

ijjk commented Oct 27, 2021

Hi, are you setting a custom global fetch anywhere in your project? This value is polyfilled by Next.js here unless global.fetch is already set.

@franklinjavier
Copy link

@ijjk nope, we're using axios

  "dependencies": {
    "@emotion/cache": "^10.0.27",
    "@emotion/css": "^10.0.27",
    "@sentry/browser": "^6.7.2",
    "axios": "^0.21.1",
    "compression": "^1.7.4",
    "connect-redis": "^6.0.0",
    "cookie-parser": "^1.4.5",
    "dayjs": "^1.10.6",
    "dnscache": "^1.0.2",
    "emotion": "^10.0.27",
    "emotion-server": "^10.0.27",
    "express": "^4.17.1",
    "express-device": "^0.4.2",
    "express-session": "^1.17.1",
    "form-data": "^4.0.0",
    "newrelic": "^7.5.2",
    "next": "^12.0.0",
    "next-seo": "^4.4.0",
    "next-transpile-modules": "^8.0.0",
    "nock": "^13.1.3",
    "passport": "^0.4.1",
    "passport-facebook": "^3.0.0",
    "passport-google-oauth20": "^2.0.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-hook-form": "^6.15.8",
    "redis": "^3.0.2",
    "request": "^2.88.2"
  },

@andreisena
Copy link
Author

I am suspecting node-fetch is being loaded by another lib before this polyfill.

@ijjk Shouldn't these global variables have it own checks?

  if(!global.Headers) global.Headers = Headers
  if(!global.Request) global.Request = Request
  if(!global.Response) global.Response = Response

@gm-rebricker
Copy link

NodeJS Version: 14.17.6

I have a similar Issue.
I call "axios.request()" on the client side which should return an AxiosPromise.
This works fine on next@11.1.2.
When I upgrade next to 12.0.0 / 12.0.1 I get the following error when I try to resolve the promise: "TypeError: Cannot read properties of undefined (reading 'then')"
The request isn't made at all, since it don't appear in the network tab of the Chrome Devtools.

@timneutkens timneutkens added Middleware Related to Next.js Middleware. kind: bug and removed bug Issue was opened via the bug report template. labels Oct 31, 2021
@timneutkens timneutkens added this to the 12.0.x milestone Oct 31, 2021
@styfle styfle modified the milestones: 12.0.x, 12.0.4 Nov 5, 2021
@rogermori
Copy link

This worked for me: set global.Response = null before to import or require the next.config.js

@timneutkens timneutkens removed this from the 12.0.5 milestone Nov 17, 2021
@javivelasco
Copy link
Member

By default Next will polyfill some fetch APIs (Request, Response, Header and fetch) only if fetch is not found in the global scope in certain entry points. If we have a custom server which is adding a global fetch (and only fetch) at the very top then the rest of APIs will not be polyfilled. We can reproduce it with the minimal Express example:

global.fetch = async function () {}

const { createServer } = require('http')
const { parse } = require('url')
const next = require('next')

const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app.prepare().then(() => {
  createServer((req, res) => {
    // Be sure to pass `true` as the second argument to `url.parse`.
    // This tells it to parse the query portion of the URL.
    const parsedUrl = parse(req.url, true)
    const { pathname, query } = parsedUrl

    if (pathname === '/a') {
      app.render(req, res, '/a', query)
    } else if (pathname === '/b') {
      app.render(req, res, '/b', query)
    } else {
      handle(req, res, parsedUrl)
    }
  }).listen(3000, (err) => {
    if (err) throw err
    console.log('> Ready on http://localhost:3000')
  })
})

With the introduction of Middleware, all web code must run in a Sandbox outside of the Node main process where we inject all polyfills. Right now we are using one dependency in the server that should not be there. I'm working on a small refactor to fix this case.

@kodiakhq kodiakhq bot closed this as completed in #31935 Dec 3, 2021
kodiakhq bot pushed a commit that referenced this issue Dec 3, 2021
This PR fixes #30398

By default Next will polyfill some fetch APIs (Request, Response, Header and fetch) only if fetch is not found in the global scope in certain entry points. If we have a custom server which is adding a global fetch (and only fetch) at the very top then the rest of APIs will not be polyfilled.

This PR adds a test on the custom server where we can add a custom polyfill for fetch with an env variable. This reproduces the issue since next-server.js will be required without having a polyfill for Response which makes it fail on requiring NextResponse. Then we remove the code that checks for subrequests to happen within the **sandbox** so that we don't need to polyfill `next-server` anymore.

The we also introduce an improvement on how we handle relative requests. Since #31858 introduced a `port` and `hostname` options for the server, we can always pass absolute URLs to the Middleware so we can always use the original `nextUrl` to pass it to fetch. This brings a lot of simplification for `NextURL` since we don't have to consider relative URLs no more.

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [x] Errors have helpful link attached, see `contributing.md`
@ijjk ijjk reopened this Dec 3, 2021
@kodiakhq kodiakhq bot closed this as completed in #32368 Dec 13, 2021
kodiakhq bot pushed a commit that referenced this issue Dec 13, 2021
**Note**: This PR is applying again changes landed #31935 that were reverted from an investigation.

This PR fixes #30398

By default Next will polyfill some fetch APIs (Request, Response, Header and fetch) only if fetch is not found in the global scope in certain entry points. If we have a custom server which is adding a global fetch (and only fetch) at the very top then the rest of APIs will not be polyfilled.

This PR adds a test on the custom server where we can add a custom polyfill for fetch with an env variable. This reproduces the issue since next-server.js will be required without having a polyfill for Response which makes it fail on requiring NextResponse. Then we remove the code that checks for subrequests to happen within the **sandbox** so that we don't need to polyfill `next-server` anymore.

The we also introduce an improvement on how we handle relative requests. Since #31858 introduced a `port` and `hostname` options for the server, we can always pass absolute URLs to the Middleware so we can always use the original `nextUrl` to pass it to fetch. This brings a lot of simplification for `NextURL` since we don't have to consider relative URLs no more.

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [x] Errors have helpful link attached, see `contributing.md`
cdierkens pushed a commit to cdierkens/next.js that referenced this issue Dec 20, 2021
**Note**: This PR is applying again changes landed vercel#31935 that were reverted from an investigation.

This PR fixes vercel#30398

By default Next will polyfill some fetch APIs (Request, Response, Header and fetch) only if fetch is not found in the global scope in certain entry points. If we have a custom server which is adding a global fetch (and only fetch) at the very top then the rest of APIs will not be polyfilled.

This PR adds a test on the custom server where we can add a custom polyfill for fetch with an env variable. This reproduces the issue since next-server.js will be required without having a polyfill for Response which makes it fail on requiring NextResponse. Then we remove the code that checks for subrequests to happen within the **sandbox** so that we don't need to polyfill `next-server` anymore.

The we also introduce an improvement on how we handle relative requests. Since vercel#31858 introduced a `port` and `hostname` options for the server, we can always pass absolute URLs to the Middleware so we can always use the original `nextUrl` to pass it to fetch. This brings a lot of simplification for `NextURL` since we don't have to consider relative URLs no more.

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [x] Errors have helpful link attached, see `contributing.md`
@balazsorban44
Copy link
Member

This issue has been automatically locked due to no recent activity. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you.

@vercel vercel locked as resolved and limited conversation to collaborators Jan 27, 2022
natew pushed a commit to natew/next.js that referenced this issue Feb 16, 2022
This PR fixes vercel#30398

By default Next will polyfill some fetch APIs (Request, Response, Header and fetch) only if fetch is not found in the global scope in certain entry points. If we have a custom server which is adding a global fetch (and only fetch) at the very top then the rest of APIs will not be polyfilled.

This PR adds a test on the custom server where we can add a custom polyfill for fetch with an env variable. This reproduces the issue since next-server.js will be required without having a polyfill for Response which makes it fail on requiring NextResponse. Then we remove the code that checks for subrequests to happen within the **sandbox** so that we don't need to polyfill `next-server` anymore.

The we also introduce an improvement on how we handle relative requests. Since vercel#31858 introduced a `port` and `hostname` options for the server, we can always pass absolute URLs to the Middleware so we can always use the original `nextUrl` to pass it to fetch. This brings a lot of simplification for `NextURL` since we don't have to consider relative URLs no more.

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [x] Errors have helpful link attached, see `contributing.md`
natew pushed a commit to natew/next.js that referenced this issue Feb 16, 2022
**Note**: This PR is applying again changes landed vercel#31935 that were reverted from an investigation.

This PR fixes vercel#30398

By default Next will polyfill some fetch APIs (Request, Response, Header and fetch) only if fetch is not found in the global scope in certain entry points. If we have a custom server which is adding a global fetch (and only fetch) at the very top then the rest of APIs will not be polyfilled.

This PR adds a test on the custom server where we can add a custom polyfill for fetch with an env variable. This reproduces the issue since next-server.js will be required without having a polyfill for Response which makes it fail on requiring NextResponse. Then we remove the code that checks for subrequests to happen within the **sandbox** so that we don't need to polyfill `next-server` anymore.

The we also introduce an improvement on how we handle relative requests. Since vercel#31858 introduced a `port` and `hostname` options for the server, we can always pass absolute URLs to the Middleware so we can always use the original `nextUrl` to pass it to fetch. This brings a lot of simplification for `NextURL` since we don't have to consider relative URLs no more.

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [x] Errors have helpful link attached, see `contributing.md`
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Middleware Related to Next.js Middleware.
Projects
None yet
10 participants