Search code examples
aws-lambdamiddy

Fixing Unknown http event format with AWS lambda and middy?


This is a test lambda. Where should the format be specified? Does middy now require event.requestContext.http.method specified somewhere?

import 'source-map-support/register';

import type { ValidatedEventAPIGatewayProxyEvent } from '@libs/apiGateway';
import { formatJSONResponse } from '@libs/apiGateway';
import { middyfy } from '@libs/lambda';

import schema from './schema';

const hello: ValidatedEventAPIGatewayProxyEvent<typeof schema> = async (event) => {
  return formatJSONResponse({
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Credentials': true,
    },
    message: `Hello ${event.body.name}, welcome to the exciting Serverless world!`,
    event,
  });
}

export const main = middyfy(hello);

The environment is

"@middy/core": "^3.1.0",
"@middy/http-cors": "^3.1.0",

With serverless: Framework Core: 3.21.0 (local) 3.21.0 (global)

Execution is via

serverless invoke local --function hello --path src/functions/hello/mock.json

"errorMessage": "[http-cors] Unknown http event format",
"errorType": "Error",
"stackTrace": [
    "Error: [http-cors] Unknown http event format",
    "    at httpCorsMiddlewareAfter (/Users/jrobens/NetBeansProjects/azuron/winpay/winpay-admin-api/node_modules/@middy/http-cors/index.cjs:82:19)",

Solution

  • @middy/http-cors support both REST (v1) and HTTP (v2) AWS events. Your test event doesn't fully comply the HTTP (v2) AWS event structure. Having it include event.requestContext.http.method will resolve this issue. Example in the AWS docs: https://docs.aws.amazon.com/lambda/latest/dg/services-apigateway.html.