Skip to content

Ignore null properties in the JSON response #1047

Closed
@hershmire

Description

@hershmire

You have already researched for similar issues?

I have searched around and have only found this StackOverflow question from over 2 years ago which was never answered.

What are you trying to achieve, or the steps to reproduce?

I would like to have the Fastify reply ignore sending back any properties that are null. Some of the endpoints I'm writing are for both admin and non-admin users. Admin users may have some additional properties on a resource response that I would prefer not to even make known if the response is from a non-admin. Wondering if there's any out-of-the-box way to do this.

Example Admin response:

{
  "firstName": "John",
  "lastName": "Doe",
  "signatureUrl": "https://example.com/signatures/123/signature.png"
}

Example Non-Admin response:

{
  "firstName": "John",
  "lastName": "Doe"
}

What was the result you received?

Currently I'm getting the following for the Non-Admin user since the signatureUrl field is nullable. I would like to not show this field at all to this type of user to reduce the overall payload size and not expose additional information that they are privy to.

Example Admin response:

{
  "firstName": "John",
  "lastName": "Doe",
  "signatureUrl": null
}

What did you expect?

Context

  • node version: 20
  • fastify version: >=4.28
  • os: Mac

I'm using Typescript with Typebox.

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions