I have a simple lambda (behind a cognito authorizer) with an http event. I am using the httpJsonParser to parse the body, then I am using a custom middleware which just validates the json using zod and last but not least I am using the httpErrorHandler middleware.
const customhandler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
return {
statusCode: 200,
body: `success
available claims : ${JSON.stringify(event.requestContext.authorizer?.claims)}`
};
};
export const handler = middy(customhandler)
.use(httpJsonBodyParser())
.use(customValidator(SOMESCHEMA))
.use(httpErrorHandler());
The customValidator looks like this:
export const customValidator = (schema: ZodSchema): middy.MiddlewareObj<APIGatewayProxyEvent, APIGatewayProxyResult> => {
const before: middy.MiddlewareFn<APIGatewayProxyEvent, APIGatewayProxyResult> = async (
request
): Promise<void> => {
if (request.event.body != null) {
try {
schema.parse(request.event.body);
} catch (e) {
throw new Error("Validation error");
}
}
};
return {
before
};
};
When I remove the .use(httpJsonBodyParser())
and the .use(httpErroHandler())
the customValidation is executed and there is no syntax error.
However as soon as I add one (or both) middlewares, with or without my custom middleware, I receive the following error when the lambda is executed:
"Runtime.UserCodeSyntaxError: SyntaxError: Unexpected token '??='",
" at _loadUserApp (/var/runtime/UserFunction.js:222:13)",
" at Object.module.exports.load (/var/runtime/UserFunction.js:300:17)",
" at Object.<anonymous> (/var/runtime/index.js:43:34)",
" at Module._compile (internal/modules/cjs/loader.js:1085:14)",
" at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)",
" at Module.load (internal/modules/cjs/loader.js:950:32)",
" at Function.Module._load (internal/modules/cjs/loader.js:790:12)",
" at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:75:12)",
" at internal/main/run_main_module.js:17:47"
My IDE and eslint is not complaining...
As suggested, there could be an issue with the build process here is my tsconfig
file:
{
"extends": "@tsconfig/node14/tsconfig.json",
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"sourceMap": true,
"outDir": "dist",
"baseUrl": ".",
"paths": {
"core/*": [
"../core/src/*"
],
"schema/*": [
"../schema/src/*"
]
}
}
}
nothing really special about it.
I upgraded to lambda node version 18.x and serverless 3 which resolved the issue.