AWS Lambda with Serverless Framework: Getting ‘Internal Server Error’ in Express App—Need Help Debugging

I’ve built a backend application using Node.js, Express, and MongoDB, and I’m attempting to deploy it on AWS using the Serverless Framework. The application works perfectly in my local environment, but when I deploy it to AWS and try to call the API using Postman, I receive a 500 Internal Server Error.

Setup Details:
• Framework: Serverless Framework
• Environment: AWS Lambda (Node.js runtime)
• API Structure:
• Using Express as the web framework
• Routes include /api/v1/users/login, /api/v1/videos, etc.
• CORS enabled
• Error handling implemented

Error Encountered:
When I send a request to my API endpoint, I receive the following response:

{ "message": "Internal Server Error" }

Code Snippet:

Here’s my src/index.js:

import dotenv from "dotenv";
import connectDB from "./db/index.js";
import { app } from "./app.js";
import serverless from "serverless-http";

dotenv.config({
  path: "./.env",
});

connectDB()
  .then(() => {
    app.on("error", (error) => {
      console.log("ERROR: ", error);
      throw error;
    });

    app.listen(process.env.PORT || 8000, () => {
      console.log(`Server is running at port: ${process.env.PORT}`);
    });
  })
  .catch((error) => {
    console.log("MONGODB connection failed !!! ", error);
  });

export const handler = serverless(app);

Here’s my src/app.js:

import express from "express";
import cors from "cors";
import cookieParser from "cookie-parser";

const app = express();

app.use(
  cors({
    origin: process.env.CORS_ORIGIN,
    credentials: true,
  })
);
// setting for handling json
app.use(
  express.json({
    limit: "16kb",
  })
);
//setting for URLS
app.use(
  express.urlencoded({
    extended: true,
    limit: "16kb",
  })
);
app.use(express.static("public"));
//config cookie-parse
app.use(cookieParser());

// routes import
import userRouter from "./routes/users.routes.js";
import videoRouter from "./routes/video.routes.js";
import commentRouter from "./routes/comment.routes.js";
import likeRouter from "./routes/like.routes.js";
import tweetRouter from "./routes/tweet.routes.js";
import subscriptionRouter from "./routes/subscription.routes.js";
import playlistRouter from "./routes/playlist.routes.js";
import dashboardRouter from "./routes/dashboard.routes.js";
import { ApiError } from "./utils/ApiError.js";

//routes declaration
app.use("/api/v1/users", userRouter);
app.use("/api/v1/videos", videoRouter);
app.use("/api/v1/comments", commentRouter);
app.use("/api/v1/likes", likeRouter);
app.use("/api/v1/tweets", tweetRouter);
app.use("/api/v1/subscription", subscriptionRouter);
app.use("/api/v1/dashboard", dashboardRouter);
app.use("/api/v1/playlist", playlistRouter);

app.use((err, req, res, next) => {
  if (err instanceof ApiError) {
    // Send a JSON response with the error details
    return res.status(err.statusCode).json({
      success: err.success,
      message: err.message,
      errors: err.errors,
    });
  }

  // For other errors, send a generic 500 response
  // res.status(500).json({
  //   success: false,
  //   message: "An unexpected error occurred.",
  // });
});

export { app };

Here’s my serverless.yml:

service: playtube-api

provider:
  name: aws
  runtime: nodejs20.x
  region: ap-south-1
  environment:
    PORT: ${env:PORT}
    CORS_ORIGIN: ${env:CORS_ORIGIN}
    MONGODB_URI: ${env:MONGODB_URI}
    ACCESS_TOKEN_SECRET: ${env:ACCESS_TOKEN_SECRET}
    ACCESS_TOKEN_EXPIRY: ${env:ACCESS_TOKEN_EXPIRY}
    REFRESH_TOKEN_SECRET: ${env:REFRESH_TOKEN_SECRET}
    REFRESH_TOKEN_EXPIRY: ${env:REFRESH_TOKEN_EXPIRY}
    CLOUDINARY_CLOUD_NAME: ${env:CLOUDINARY_CLOUD_NAME}
    CLOUDINARY_API_KEY: ${env:CLOUDINARY_API_KEY}
    CLOUDINARY_API_SECRET: ${env:CLOUDINARY_API_SECRET}
    CLOUDINARY_URL: ${env:CLOUDINARY_URL}

functions:
  api:
    handler: src/index.handler
    events:
      - httpApi:
          path: /{proxy+}
          method: ANY

plugins:
  - serverless-dotenv-plugin

It’s my first time using it and deploying backend server kindly help me, I would be grateful.

1

You don’t need to listen to a port unless you are using environment like local or AWS EC2. Lambda just wants a handler.

import dotenv from "dotenv";
import connectDB from "./db/index.js";
import { app } from "./app.js";
import serverless from "serverless-http";

dotenv.config({
   path: "./.env",
});

connectDB()
.catch((error) => {
    console.log("MONGODB connection failed !!! ", error);
});

export const handler = serverless(app);

Also app.on('error') doesn’t works in express, app.use((err, req, res, next) is enough to catch errors.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật