Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Utility toWebRequest crashes server when body has already been received #578

@passionate-bram

Description

@passionate-bram

Environment

  • Environment: Netlify, indicates nodejs:18.v18.
  • h3: 1.8.2
  • nitropack: 2.7.2

Note: This is not a nitropack bug because the fault lies with the utilities provided by h3.
It is possible to create a workaround using different h3 functions, therefor the failing function is faulty.

Reproduction

  1. Create a nitro project, add a route containing the following handler:
    export default defineEventHandler(async event => {
      if (event.method !== 'POST') {
        return `<form action="${getRequestURL(event)}" method=POST><button name=btn autofocus>Submit`;
      } else {
        return Object.fromEntries((await readFormData(event)).entries());
      }
    });
  2. Publish on netlify
  3. Open the route in a browser
  4. Click submit button
  5. 💥

Locally, you get what you expect:

{"btn": ""}

Describe the bug

Using readFormData crashes the server, not even allowing an error to be caught with catch or similar mechanisms.

I cannot see exactly why the server crashes, as I only receive a cryptic error back:

error decoding lambda response: invalid status code returned from lambda: 0

Additional context

Root cause of nitrojs/nitro#1721

That said, I do know that toWebRequest() is the function within readFormData that is at fault.
The event.node.req.body field is a string containing the POST body of the request before calling into readFormData.

Using the following implementation of readFormData can succesfully read the data:

async function readFormData_fixed(event: H3Event) : Promise<FormData> {
  const request = new Request(getRequestURL(event), {
    // @ts-ignore Undici option
    duplex: 'half',
    method: event.method,
    headers: event.headers,
    body: await readRawBody(event),
  } as RequestInit);
  return await request.formData();
}

Here readRawBody short-circuits because event.node.req.body is set and RequestInit.body is allowed to be of type string.

Logs

Logging statements directly before `await readFormData(...)` show up in netlify's function log.
Logging statements directly after `await readFormData(...)` do not.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions