Skip to content

Static GET App route throws TypeError when returning cached 204 #49005

Open

Description

@jmurty

Verify canary release

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

Provide environment information

From next info:

    Operating System:
      Platform: darwin
      Arch: arm64
      Version: Darwin Kernel Version 22.6.0: Wed Jul  5 22:22:05 PDT 2023; root:xnu-8796.141.3~6/RELEASE_ARM64_T6000
    Binaries:
      Node: 16.16.0
      npm: 8.11.0
      Yarn: 1.22.19
      pnpm: N/A
    Relevant Packages:
      next: 13.4.20-canary.12
      eslint-config-next: N/A
      react: 18.2.0
      react-dom: 18.2.0
      typescript: 4.9.5
    Next.js Config:
      output: N/A

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

App directory (appDir: true)

Link to the code that reproduces this issue

https://github.com/jmurty/next-issue-204-static

To Reproduce

  • Implement a static (non-dynamic) app route endpoint with a GET function that returns a HTTP 204 No Content response
  • Run project with a production build, either self-hosted (e.g. yarn build && yarn start) or deployed to Vercel
  • Project builds correctly, including generation of static page for the 204 app route
  • Send a GET request to the 204 app route – e.g. curl -v https://next-issue-204-static.vercel.app/api/get-204-static
  • Receive a 500 Server Error response, and get a server-side a stack trace similar to the one below
  • Note that nearly identical static app routes that return other 2xx HTTP response codes work as expected – e.g. curl -v https://next-issue-204-static.vercel.app/api/get-201-static
TypeError: Response constructor: Invalid response status code 204
    at webidl.errors.exception (node:internal/deps/undici/undici:1265:14)
    at initializeResponse (node:internal/deps/undici/undici:6845:31)
    at new Response (node:internal/deps/undici/undici:6654:9)
    at NextNodeServer.renderToResponseWithComponentsImpl (/var/task/node_modules/next/dist/server/base-server.js:1221:61)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async NextNodeServer.renderPageComponent (/var/task/node_modules/next/dist/server/base-server.js:1288:24)
    at async NextNodeServer.renderToResponseImpl (/var/task/node_modules/next/dist/server/base-server.js:1319:32)
    at async NextNodeServer.pipeImpl (/var/task/node_modules/next/dist/server/base-server.js:630:25)
    at async Object.fn (/var/task/node_modules/next/dist/server/next-server.js:1144:21)
    at async Router.execute (/var/task/node_modules/next/dist/server/router.js:315:32) {
  page: '/api/get-204-static'
}

Note that the linked reproduction project is also deployed to the Vercel project next-issue-204-static and the static app route that returns 204 is available at https://next-issue-204-static.vercel.app/api/get-204-static

Describe the Bug

Static app routes do not correctly cache and return HTTP 204 No Content responses.

At build time the static app route is generated without error, but when a request arrives at the endpoint the cached result is not returned. Instead, it seems like the server re-runs the app route and in doing so triggers the server error TypeError: Response constructor: Invalid response status code 204

Expected Behavior

An app route that returns a HTTP 204 No Content response should have the result cached at build time, and the 204 response returned upon request.

Only the 204 HTTP response status code seems to be affected. As well as showing the problem 204 case, the example project (and Vercel deployment) includes nearly identical static app routes that return other 2xx status codes. All of the routes work as expected except the one that returns 204:

Which browser are you using? (if relevant)

No response

How are you deploying your application? (if relevant)

next start & Vercel

Activity

  1. added
    bug
    on Apr 30, 2023
  2. mlhmz commented on May 11, 2023

    @mlhmz

    +1 Same issue here.

    In the Doc Entry https://nextjs.org/docs/messages/invalid-api-status-body is a fix provided, but its for the old NextApiHandler with NextApiRequest and NextApiResponse

  3. jmurty commented on May 15, 2023

    @jmurty
    Author

    It's interesting that returning no response data fixes the problem for the pages/ routing.

    In the App Router APIs there isn't a clear way to return no response data, because a first body argument is required to construct a Response object where you can set the HTTP response status code with the second argument. In the example project I use null for the body, and I have also tried undefined and an empty string: all cause errors either at build time (for anything but null) or later at request time.

    Here's the example endpoint code: https://github.com/jmurty/next-issue-204-static/blob/main/app/api/get-204-static/route.js

    My guess about what might be going on: the null response body is not cached when run at build time, which makes sense, but when the body is later fetched from the cache at run time a default missing value other than null is returned, perhaps undefined? The Response() constructor throws if you provide any body argument other than null when using HTTP response code 204.

  4. MinnieMinwoo commented on Aug 30, 2023

    @MinnieMinwoo

    While attempting to resolve the same issue, I find this issue and leave a comment for other people. I'm not sure if there was an update in a few months, but in the current version, if you use a NextResponse object using undefined, it works fine without errors.

    export async function GET() {
      console.log("204 status code test");
      return new NextResponse(undefined, { status: 204 });
    }
  5. jmurty commented on Aug 30, 2023

    @jmurty
    Author

    Hi @MinnieMinwoo thanks for the feedback. I have updated my test project to the latest canary release 13.4.20-canary.12 and tried your work-around but I get the same error on the built and deployed test site, even using NextResponse.

    I added a new API route /api/get-204-static-nextresponse to test the work-around, code here:
    https://github.com/jmurty/next-issue-204-static/blob/main/app/api/get-204-static-nextresponse/route.js

    I tried a few other things as well, but as far as I can tell the original issue still remains unless there is something in your work-around that I'm missing?

  6. jmurty commented on Aug 30, 2023

    @jmurty
    Author

    Updated issue description to note that test project is updated to version 13.4.20-canary.12

  7. MinnieMinwoo commented on Sep 3, 2023

    @MinnieMinwoo
    스크린샷 2023-09-03 16 12 34 스크린샷 2023-09-03 16 14 50

    I tried to replicate and test the repository in the same environment as possible, but I couldn't reproduce the error like the screenshot result.
    What's unusual is that even the previous "get-204 static" page, which was expected to fail in the newly cloned project, does not fail and the routing succeeds normally.
    I think something's wrong with the project setup. In the case of my project, I tried to reproduce the 204 response error on another computer, but it was printed normally without the error.
    I'm sorry I couldn't help you. Lastly, I am leaving the environmental information that I executed your project.

    Operating System:
          Platform: darwin
          Arch: x64
          Version: Darwin Kernel Version 22.6.0: Wed Jul  5 22:21:56 PDT 2023; root:xnu-8796.141.3~6/RELEASE_X86_64
        Binaries:
          Node: 16.20.2
          npm: 8.19.4
          Yarn: 1.22.19
          pnpm: N/A
        Relevant Packages:
          next: 13.4.20-canary.12
          eslint-config-next: N/A
          react: 18.2.0
          react-dom: 18.2.0
          typescript: 4.9.5
        Next.js Config:
          output: N/A
    
  8. jmurty commented on Sep 3, 2023

    @jmurty
    Author

    The error doesn't happen in dev mode, it only happens when running in production builds, e.g. after deploying to Vercel or running locally with yarn build && yarn start

  9. MinnieMinwoo commented on Sep 3, 2023

    @MinnieMinwoo

    I found out the cause of error and put the pr on it. I think it's better to modify the code like this before PR.

    /node_modules/next/dist/server/base-server.js
    // search "await (0, _sendresponse.sendResponse)(req, res, new Response"
    const nullBodyStatus = [101, 204, 205, 304];
    await (0, _sendresponse.sendResponse)(req, res, new Response(nullBodyStatus.includes(cachedData.status) ? null : cachedData.body, {
            headers: (0, _utils3.fromNodeOutgoingHttpHeaders)(headers),
            status: cachedData.status || 200,
    }));
  10. jmurty commented on Sep 3, 2023

    @jmurty
    Author

    @MinnieMinwoo Thanks for finding the relevant code and submitting a PR, hopefully this will lead to a full fix. In the meantime your workaround patch is very helpful!

  11. reza-ebrahimi commented on Sep 6, 2023

    @reza-ebrahimi

    Seems its not implemented yet for NextResponse, use as following:

    export async function GET(request: Request) {
      return new Response(null, {
        status: 200,
      })
    }
    
    export async function DELETE(request: Request) {
      return new Response(null, {
        status: 204,
      })
    }
  12. MinnieMinwoo commented on Sep 7, 2023

    @MinnieMinwoo

    I did the test before for debugging, I had the same problem using the Response object. When I run server in dev enviroment, both NextResponse and Response objects work fine. If certain conditions are met during the build process, the response seems to be unintentionally deformed while caching the api. In my case, it worked well when I use AWS amplify hosting, but the same problem occurred when I ran it locally.

  13. Flafi87 commented on Nov 30, 2023

    @Flafi87

    Hello,
    We are using app router and returning 204 is still causing an error

    export const postAccessRequest = async (req: NextRequest) => {
      const session = await getServerSessionDirectly()
    
      try {
        const body = await req.json()
        const { teamId } = body
    
        const isTeamAdmin = await checkIfUserTeamAdmin({ teamId, userId: session?.account?.id })
    
        if (!isTeamAdmin) {
          throw new Error("Only team leader is allowed to perform this action")
        }
    
        const result = await createServiceAccount(session?.account?.email)
        if (!result.ok) {
          throw new Error("An error occurred while creating service account")
        }
        return NextResponse.json({}, { status: 204 })
      } catch (error) {
        withErrorHandling(req, error)
      }
    }

    Error

    ⨯ Error: No response is returned from route handler '\src\app\api\v4\gcp-service-account-request\route.ts'. Ensure you return a `Response` or a `NextResponse` in all branches of your handler.
        at \node_modules\next\dist\compiled\next-server\app-route.runtime.dev.js:6:62774
        at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    [14:58:16.921] ERROR (18628): Unexpected error: Response constructor: Invalid response status code 204;

    Next info

    Operating System:
      Platform: win32
      Arch: x64
      Version: Windows 11 Pro
    Binaries:
      Node: 20.9.0
      npm: N/A
      Yarn: N/A
      pnpm: N/A
    Relevant Packages:
      next: 14.0.3
      eslint-config-next: 14.0.3
      react: 18.2.0
      react-dom: 18.2.0
      typescript: 5.2.2
    Next.js Config:
      output: N/A
  14. jmurty commented on Dec 1, 2023

    @jmurty
    Author

    Hi @Flafi87 from the look of your code your route shouldn't be static, since it handles data from the requests and also (maybe?) a per-user session? If your route is acting like a static one, you should probably fix it to be dynamic instead.

    If the route is already dynamic and is throwing an error for 204 responses, you might be experiencing a different issue than the one I originally reported, because my experience was specific to static routes.

  15. removed
    bug
    on Jan 23, 2025
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

    No labels
    No labels

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions