Skip to content

The usage of NextResponse.json() function leads to the error TypeError: Response.json is not a function. in dev mode #48524

Closed

Description

@aleksFedotov

Verify canary release

  • I verified that the issue exists in the latest Next.js canary release

Provide environment information

Operating System:
      Platform: win32
      Arch: x64
      Version: Windows 10 Home Single Language
    Binaries:
      Node: 18.2.0
      npm: N/A
      Yarn: N/A
      pnpm: N/A
    Relevant packages:
      next: 13.3.1-canary.12
      eslint-config-next: 13.3.0
      react: 18.2.0
      react-dom: 18.2.0

Which area(s) of Next.js are affected? (leave empty if unsure)

App directory (appDir: true), Middleware / Edge (API routes, runtime)

Link to the code that reproduces this issue

https://github.com/aleksFedotov/next-js-error

To Reproduce

npm install
npm run dev

Describe the Bug

When using NextResponse.json() in development mode, an error occurs.
error - TypeError: Response.json is not a function
at Function.json (webpack-internal:///(sc_server)/./node_modules/next/dist/server/web/spec-extension/response.js:67:35)
at GET (webpack-internal:///(sc_server)/./app/api/hello/route.ts:8:95)
at eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:232:24)
at eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/lib/trace/tracer.js:108:36)
at NoopContextManager.with (webpack-internal:///(sc_server)/./node_modules/next/dist/compiled/@opentelemetry/api/index.js:360:30)
at ContextAPI.with (webpack-internal:///(sc_server)/./node_modules/next/dist/compiled/@opentelemetry/api/index.js:30:58)
at NoopTracer.startActiveSpan (webpack-internal:///(sc_server)/./node_modules/next/dist/compiled/@opentelemetry/api/index.js:953:34)
at ProxyTracer.startActiveSpan (webpack-internal:///(sc_server)/./node_modules/next/dist/compiled/@opentelemetry/api/index.js:993:36)
at eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/lib/trace/tracer.js:97:107)
at NoopContextManager.with (webpack-internal:///(sc_server)/./node_modules/next/dist/compiled/@opentelemetry/api/index.js:360:30)
at ContextAPI.with (webpack-internal:///(sc_server)/./node_modules/next/dist/compiled/@opentelemetry/api/index.js:30:58)
at NextTracerImpl.trace (webpack-internal:///(sc_server)/./node_modules/next/dist/server/lib/trace/tracer.js:97:32)
at eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:227:49)
at AsyncLocalStorage.run (node:async_hooks:327:14)
at Object.wrap (webpack-internal:///(sc_server)/./node_modules/next/dist/server/async-storage/static-generation-async-storage-wrapper.js:37:24)
at eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:181:93)
at AsyncLocalStorage.run (node:async_hooks:327:14)
at Object.wrap (webpack-internal:///(sc_server)/./node_modules/next/dist/server/async-storage/request-async-storage-wrapper.js:64:24)
at AppRouteRouteModule.execute (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:180:87)
at AppRouteRouteModule.handle (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:272:41)
at RouteHandlerManager.handle (C:\Coding\practice\error\node_modules\next\dist\server\future\route-handler-managers\route-handler-manager.js:28:29)
at doRender (C:\Coding\practice\error\node_modules\next\dist\server\base-server.js:919:58)
at cacheEntry.responseCache.get.incrementalCache.incrementalCache (C:\Coding\practice\error\node_modules\next\dist\server\base-server.js:1130:34)
at C:\Coding\practice\error\node_modules\next\dist\server\response-cache\index.js:96:42
at ResponseCache.get (C:\Coding\practice\error\node_modules\next\dist\server\response-cache\index.js:144:11)
at DevServer.renderToResponseWithComponentsImpl (C:\Coding\practice\error\node_modules\next\dist\server\base-server.js:1049:53)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async DevServer.renderPageComponent (C:\Coding\practice\error\node_modules\next\dist\server\base-server.js:1270:24)
at async DevServer.renderToResponseImpl (C:\Coding\practice\error\node_modules\next\dist\server\base-server.js:1301:32)
at async DevServer.pipeImpl (C:\Coding\practice\error\node_modules\next\dist\server\base-server.js:619:25)
at async Object.fn (C:\Coding\practice\error\node_modules\next\dist\server\next-server.js:1126:21)
at async Router.execute (C:\Coding\practice\error\node_modules\next\dist\server\router.js:311:32)
at async DevServer.runImpl (C:\Coding\practice\error\node_modules\next\dist\server\base-server.js:593:29)
at async DevServer.run (C:\Coding\practice\error\node_modules\next\dist\server\dev\next-dev-server.js:922:20)
at async DevServer.handleRequestImpl (C:\Coding\practice\error\node_modules\next\dist\server\base-server.js:528:20)

However, in production mode, there is no such error. Also, if you use this function on Linux instead of Windows 11, the error disappears.

Expected Behavior

Produce a response with the given JSON body.

Which browser are you using? (if relevant)

No response

How are you deploying your application? (if relevant)

No response

Activity

  1. added
    bugIssue was opened via the bug report template.
    on Apr 18, 2023
  2. mpurdon commented on Apr 18, 2023

    @mpurdon

    I am also experiencing this issue in version 13.2.4

    Operating System:
          Platform: osx
          Arch: M1 Max
          Version: MacOS Monterey 12.6
        Binaries:
          Node: v18.0.0
          npm: 9.2.0
          Yarn: N/A
          pnpm: N/A
        Relevant packages:
          next: 13.2.4
          eslint-config-next: 13.2.4
          react: 18.2.0
          react-dom: 18.2.0
    
  3. joacub commented on Apr 18, 2023

    @joacub

    may be related:
    #48542

  4. Tvlasev commented on Apr 30, 2023

    @Tvlasev

    I have the same problem when using NextResponse.json(). Also I am getting a 500 server error status code when I am trying to make a post request to a mongodb database and yet the data is successfully created in the db

  5. pago commented on May 3, 2023

    @pago

    I ran into this issue while updating one of our apps to use App Router. The source of the problem in our case turned out to be that we explicitly disabled experimental-fetch.

    # before
    NODE_OPTIONS='--no-experimental-fetch' next dev
    
    # after
    next dev

    After removing the --no-experimental-fetch flag, everything worked as expected.

  6. prashantchothani commented on May 5, 2023

    @prashantchothani

    I am facing the same issue even in next dev. I am getting the following error:

    TypeError: next_dist_server_web_exports_next_response__WEBPACK_IMPORTED_MODULE_2__.default.json is not a constructor
    at GET (webpack-internal:///(sc_server)/./app/api/cms/masters/meals/route.js:38:12)
    at runMicrotasks ()
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:244:37)

  7. Aoichaan0513 commented on May 5, 2023

    @Aoichaan0513

    I initially had the same problem in my environment, but by upgrading the Node.js version from 18.0.0 to 18.16.0, the latest stable version, the error no longer occurred.

  8. alexshenker commented on May 7, 2023

    @alexshenker

    I'm getting this error while trying to implement NextJS' own exmple:

    export async function GET(request: Request) {
      return NextResponse.json({ hello: "Next.js" });
    }
    

    with Node v18.2.0 / Mac M1

  9. hj007jacky commented on May 10, 2023

    @hj007jacky

    use this:
    return new NextResponse(
    JSON.stringify({ success: false, message: 'authentication failed' }),
    { status: 401, headers: { 'content-type': 'application/json' } },
    );

  10. added
    UpstreamRelated to using Next.js with a third-party dependency. (e.g., React, UI/icon libraries, etc.).
    on May 25, 2023
  11. balazsorban44 commented on May 25, 2023

    @balazsorban44
    Contributor

    Next.js relies on the runtime environment to provide the Response.json method.

    Node.js 18.2 did not have this method yet, it was added in 18.3. See: nodejs/node#43197 (comment)

    You can upgrade your runtime environment to at least 18.3 and it should fix this issue.

  12. machineghost commented on Jun 12, 2023

    @machineghost

    Please re-open this issue, as updating to Node does not resolve it:

    $ node --version
    v20.3.0
    
    $ npm run dev
    

    ... try to hit API ...

    - error TypeError: next_dist_server_web_exports_next_response__WEBPACK_IMPORTED_MODULE_0__.json is not a function
    
  13. 5 remaining items

  14. jonnylangefeld commented on Jun 22, 2023

    @jonnylangefeld

    If anyone else comes here: I found what my issue was. It was the import 'jest-fetch-mock', which I needed on an earlier node version. During the debugging of this issue I then updated the node version to v20.3.1 but left import 'jest-fetch-mock' in the jest.setup.js file. However, that mock didn't have the Response.json() function cause it's not updated yet.

    The solution was just to remove that import once I was on node v20.3.1 and now it works in both, jest and npm run dev 🥳

  15. n1kolayb commented on Jun 30, 2023

    @n1kolayb

    My issue was due to json static method was not available in the target browsers like Firefox and Safari:
    https://developer.mozilla.org/en-US/docs/Web/API/Response/json_static

    @hj007jacky solution works like a charm =)

  16. machineghost commented on Jul 1, 2023

    @machineghost

    I'm found the problem: it's an import issue.

    When I have this, I get the error:

    import { NextResponse  } from 'next/server';
    
    export async function GET(request) {
      return NextResponse.json({ success: true });
    }
    

    But when I change the import like so, it works:

    import Server from 'next/server';
    
    export async function GET(request) {
      return Server.NextResponse.json({ success: true });
    }
    

    So it appears that some sort of export-related issue causes this problem ... for users like me, but not for other users (and I'm not sure what's different about my environment).

    P.S. If I import both, and log them side-by-side ...

    import Server, { NextResponse } from 'next/server';
    
    console.log(Server.NextResponse, NextResponse);
    

    They appear to be identical:

    [class NextResponse extends Response] [class NextResponse extends Response] 
    

    ... but again, Server.NextResponse works perfectly, while NextResponse (the direct named import) fails with the error.

  17. reubendrummond commented on Jul 3, 2023

    @reubendrummond

    I had this issue and none of the above fixes worked. Turns out I just needed to install jest-environment-node.

    See here

  18. darcy-vitacca commented on Jul 10, 2023

    @darcy-vitacca

    If we need to upgrade node version for this to work it does but vercel only has up to node 18 so what is the solution for a deployed version?

    Tried with these and can't get it working locally
    "next": "^13.4.8",
    "node": "v18.0.0"

    error NotSupportedError: multipart/form-data not supported
    at NextRequest.formData (node:internal/deps/undici/undici:6056:17)
    at POST (webpack-internal:///(sc_server)/./app/api/protected/train-upload/route.ts:41:40)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:249:37) {
    code: 'UND_ERR_NOT_SUPPORTED'

    error TypeError: Response.json is not a function
    at Function.json (webpack-internal:///(sc_server)/./node_modules/next/dist/server/web/spec-extension/response.js:67:35)
    at POST (webpack-internal:///(sc_server)/./app/api/protected/train-upload/route.ts:166:99)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:249:37)

    `
    export async function POST(request: NextRequest) {

    let stream;
    const encoder = new TextEncoder();
    
    try {
    
        / LINE BELOW CAUSING ISSUE
    
        const formData = await request.formData();
        
         ..... more code
    

    }
    `

  19. mathesond2 commented on Jul 13, 2023

    @mathesond2

    Ran into this problem earlier today, updating my Node.js to 18.16.1 resolved the issue. I'd previously tried the import Server from 'next/server' solution above and that did not solve my issue.

    This runtime env dependency (at least Node.js v 18.3) should be outlined further in the docs, IMO.

  20. mjewell commented on Jul 21, 2023

    @mjewell

    I made a package that exports some utility functions for making route handlers. Those functions use NextResponse from next/server and I was running into the same issue, but it varied depending on the runtime of my route handlers.

    app using nodejs runtime

    • using Server.NextResponse it works
    • using NextResponse it errors as described above

    app using edge runtime

    • using NextResponse it works
    • using Server.NextResponse it errors saying next/server doesn't have a default export

    No idea why it was doing that, but I was able to fix it by adding a file like this:

    // ./next-server-bugfix.ts
    import {
      NextRequest as NextRequest1,
      NextResponse as NextResponse1,
    } from "next/server";
    
    export type NextRequest = NextRequest1;
    
    const NextResponseBase = NextResponse1["default"] || NextResponse1;
    export class NextResponse extends NextResponseBase {}

    and updating all my imports within my package to from next/server to ./next-server-bugfix.

  21. joeebw commented on Jul 25, 2023

    @joeebw

    I initially had the same problem in my environment, but by upgrading the Node.js version from 18.0.0 to 18.16.0, the latest stable version, the error no longer occurred.

    This worked for me! Thank you

  22. vrajpal-jhala commented on Aug 4, 2023

    @vrajpal-jhala

    It's not working for me when I add "type": "module" in my package.json. Any suggestions?

  23. Stalex89 commented on Aug 8, 2023

    @Stalex89

    I suppose the ticket can be reopened because the issue is stil there when project is deployed to the Vercel (even thought the Node.js version on Vercel is set to 18.x).

    "next": "13.4.12"

    The temporary fix by @mjewell worked for me, thank you!

  24. EbodShojaei commented on Aug 17, 2023

    @EbodShojaei

    Please reopen. I've also ran into a similar issue with "next": "^13.4.13". Regardless of importing import Server from 'next/server'; or import { NextResponse } from 'next/server'; I get an error 500. Moreover, I also get a TypeError if I don't prefix new to my NextResponse or Server.NextResponse. I'm worried any hacky fixes will cause long-term errors as library versions update in the future.

    import Server from 'next/server';
    
    export async function GET(request) {
    return new Server.NextResponse(200).json(fullURL); // {url: fullURL} did not fix
    
  25. sloba88 commented on Aug 23, 2023

    @sloba88

    I have the same error when trying to do a simple upload with request.formData() on Node 18.2.0. Updating node to 18.17 or 20 solves the problem but Vercel runs 18.x so it doesn't work on server

    error NotSupportedError: multipart/form-data not supported at NextRequest.formData (node:internal/deps/undici/undici:1783:17)

  26. github-actions commented on Sep 7, 2023

    @github-actions
    Contributor

    This closed issue has been automatically locked because it had no new activity for 2 weeks. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you.

  27. locked as resolved and limited conversation to collaborators on Sep 7, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    RuntimeRelated to Node.js or Edge Runtime with Next.js.UpstreamRelated to using Next.js with a third-party dependency. (e.g., React, UI/icon libraries, etc.).bugIssue was opened via the bug report template.locked

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions