Skip to content

httpResponseSerializer generates type error in Middy 7.1.4 #1590

@james-a-henderson-govdocs

Description

Describe the bug
Version 7.1.3 changed the type for the serializer function from (response: any) to (response: unknown). This is causing type errors when using the httpResponseSerializer that were not there before.

To Reproduce
How to reproduce the behaviour:

index.ts:

import middy from "@middy/core"
import httpResponseSerializer from "@middy/http-response-serializer"

export const handler = middy<any, {statusCode: number, body: any}>()
  .use(httpResponseSerializer({
    serializers: [
      {
        regex: /^application\/json$/,
        // taken directly from the documentation
        serializer: ({body}) => JSON.stringify(body)
      }
    ],
    defaultContentType: 'application/json'
  }))
  .handler((event, context) => {
    const body = { foo: 'bar' }

    return {
      statusCode: 200,
      body
    }
  })

package.json:

{
  "type": "module",
  "main": "index.ts",
  "devDependencies": {
    "@tsconfig/node22": "^22.0.5",
    "@types/aws-lambda": "^8.10.161",
    "typescript": "^5.9.3"
  },
  "dependencies": {
    "@middy/core": "7.1.4",
    "@middy/http-response-serializer": "7.1.4"
  }
}

tsconfig.json:

{
  "extends": "@tsconfig/node22/tsconfig.json"
}

Running npx tsc with this setup gives the following error:

index.ts:9:9 - error TS2322: Type '({ body }: { body: any; }) => string' is not assignable to type '(response: unknown) => string | { [key: string]: unknown; body: string; }'.
  Types of parameters '__0' and 'response' are incompatible.
    Type 'unknown' is not assignable to type '{ body: any; }'.

9         serializer: ({body}) => JSON.stringify(body)
          ~~~~~~~~~~

  node_modules/@middy/http-response-serializer/index.d.ts:7:2
    7  serializer: (
       ~~~~~~~~~~
    The expected type comes from property 'serializer' which is declared here on type 'SerializerHandler'


Found 1 error in index.ts:9

Expected behaviour
Ideally the response type should be inferred from the middy handler chain, giving full type safety. Barring that, it should revert to the behavior of 7.1.2, as this is a breaking change which should not happen on a minor version.

Environment (please complete the following information):

  • Node.js: 22
  • Middy: 7.1.4

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions