Skip to content

reply.send(string) does not serialize strings as JSON even if the Content-Type is set to application/json #6291

@FlandiaYingman

Description

@FlandiaYingman

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

5.5.0

Plugin version

No response

Node.js version

22.14.0

Operating system

Windows

Operating system version (i.e. 20.04, 11.3, 10)

24H2

Description

According to the documentation, if Content-Type is set to application/json; charset=utf-8, reply.send(string) should serialize the string in JSON as an object. The current behavior does not match the documentation, which send the string in raw without any serialization.

Code to reproduce:

fastify.get(
  "/",
  async function (request, reply) {
    return reply
      .type("application/json; charset=utf-8")
      .send("Hello");
  },
);

It is expected to return "Hello", but it returns Hello instead. I checked the relevant logic and it seems that the problem comes from:

fastify/lib/reply.js

Lines 203 to 206 in b84733e

if (typeof payload !== 'string') {
preSerializationHook(this, payload)
return this
}

which serializes the payload only if it is not a string.

Link to code that reproduces the bug

Provided in the description.

Expected Behavior

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugConfirmed bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions