Amal Mathew
Amal Mathew

Reputation: 1

Import module error when Lambda is deployed - Node

I am getting an ImportModuleError after the Lambda is deployed. The function works fine locally (I tried with serverless-offline and it works fine), but when trying to invoke the deployed function, it is giving the following error. reflect-metadata is correctly added among the dependancies in package.json

2024-03-26T02:52:13.927Z undefined ERROR Uncaught Exception { "errorType": "Runtime.ImportModuleError", "errorMessage": "Error: Cannot find module 'reflect-metadata'\nRequire stack:\n- /var/task/dist/functions/OrderHandler.js\n- /var/runtime/index.mjs", "stack": [ "Runtime.ImportModuleError: Error: Cannot find module 'reflect-metadata'", "Require stack:", "- /var/task/dist/functions/OrderHandler.js", "- /var/runtime/index.mjs", at _loadUserApp (file:///var/runtime/index.mjs:1087:17)", at async UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1119:21)", at async start (file:///var/runtime/index.mjs:1282:23)", at async file:///var/runtime/index.mjs:1288:1" ] }


import 'reflect-metadata';
import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';
import { OrdersController } from './OrdersController';

export const handler = async (
  event: APIGatewayProxyEvent,
): Promise<APIGatewayProxyResult> => {
  try {
    const path = event.path;
    const method = event.httpMethod;

    container.registerSingleton<OrderRepository>(
      'OrderRepository',
      OrderRepository,
    );
    const OrdersController = new OrdersController();

    console.log(path);
    // Route handling
    switch (true) {
      case path === '/orders' && method === 'GET':
        return OrdersController.handler(event);
      default:
        return {
          statusCode: 404,
          body: JSON.stringify({ message: 'Route not found' }),
        };
    }
  } catch (error) {
    console.error('Error:', error);
    return {
      statusCode: 500,
      body: JSON.stringify({ message: 'Internal server error' }),
    };
  }
};

Can anyone please advice on what could be potentially wrong?

I tried to invoke the lambda function, but it failed with the above error.

Upvotes: 0

Views: 293

Answers (1)

Ashlok Choudhary
Ashlok Choudhary

Reputation: 11

You can create a Lambda Layer containing the necessary dependencies for your application and bind it to your Lambda function. This approach helps keep your deployment package small and ensures that your Lambda function has all the required dependencies to run efficiently.

You can refer to this documentation for creating one: https://docs.aws.amazon.com/lambda/latest/dg/creating-deleting-layers.html

Upvotes: 0

Related Questions